package com.bml.architect.rocketmq.producer;

import com.bml.architect.rocketmq.config.ExtRocketMQTemplate;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class DefaultProducer {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ExtRocketMQTemplate extRocketMQTemplate;


    public void sendTxExtMsg(String topic, String message) {
        for (int i = 0; i < 10; i++) {
            Message<String> msg = MessageBuilder.withPayload(message + i).build();
            String destination = topic + ":TAG_TX";
            TransactionSendResult sendResult = extRocketMQTemplate.sendMessageInTransaction(destination, msg, String.valueOf(i));
            System.out.printf("%s%n", sendResult);
        }
    }

    /**
     * 发送普通的消息
     *
     * @param topic
     * @param message
     */
    public void sendMsg(String topic, String message) {
        rocketMQTemplate.convertAndSend(topic, message);
    }


    /**
     * 发送事务消息
     *
     * @param topic
     * @param msg
     */
    public void sendTxMsg(String topic, String msg) {
        String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 0; i < 10; i++) {
            String tag = tags[i % tags.length];
            Message<String> message = MessageBuilder.withPayload(msg + i).build();
            String destinion = topic + ":" + tag;
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(destinion, message, destinion);
            System.out.printf("%s%n", transactionSendResult);
        }
    }
}
